local class = reload("class")
local httpS = require("httpS")
local super = reload("super.basic")
local cjson = require("cjson")
local conver = require("json.conver")
local clear = reload("table.opt.clear")

---@class httpLS:super.basic
local this = class(super)

function this:ctor(name, url)
    super.ctor(self)
    self._name = name
    self._url = url
end

---启动请求
function this:launch()
    httpS.new(self._name, self._url, self)
    return self:hand()
end

function this:hand()
    return function (hand)
        self._hand = hand
    end
end

---监听回调
function this:listen()
    httpS.set(self._name, self:cors())
end

local cors = {}
local funs = {}
local keys = {
    get = "GET",
    post = "POST",
    opts = "OPTIONS",
    put = "PUT",
    del = "DELETE",
    head = "HEAD"
}
---跨域处理信息
function this:cors()
    ---统计监听方法
    clear(funs)
    for k, _ in pairs(self._hand) do
        table.insert(funs, keys[k])
    end

    ---填充跨域信息
    clear(cors)
    cors["Access-Control-Allow-Origin"] = "*"
    cors["Access-Control-Allow-Methods"] = table.concat(funs, ",")
    cors["Access-Control-Allow-Headers"] = "Content-Type, Accept, X-Requested-With"
    cors["Access-Control-Allow-Credentials"] = "true"
    cors["Access-Control-Max-Age"] = "3600"
    return cors
end

---回复请求
---@param ask userdata @请求句柄
---@param method string @请求方法
---@param... any @请求参数
function this:reply(ask, method, uri, args)
    local hand = self._hand
    local f = hand[method]
    if f then
        f(ask, uri, conver(args))
    else
        self:ret(ask, { code = 404, msg = "method not found" })
    end
end

---返回请求
---@param ask userdata @请求句柄
---@param tab table @返回结果
function this:ret(ask, tab)
    httpS.ret(ask, cjson.encode(tab))
end

---返回请求
---@param ask userdata @请求句柄
---@param str string @返回结果
function this:retjs(ask, str)
    httpS.ret(ask, str)
end

---转json
function this:encode(tab)
    return cjson.encode(tab)
end

---转lua
function this:decode(str)
    return cjson.decode(str)
end

return this
